package cn.craftyun.serverlist.controller;

import cn.craftyun.serverlist.entity.User;
import cn.craftyun.serverlist.entity.UserRole;
import cn.craftyun.serverlist.param.UpdateUserParam;
import cn.craftyun.serverlist.param.UserLoginParam;
import cn.craftyun.serverlist.param.UserUpdateInfoParam;
import cn.craftyun.serverlist.param.UserUpdatePassParam;
import cn.craftyun.serverlist.service.IServerService;
import cn.craftyun.serverlist.service.IUserService;
import cn.craftyun.serverlist.vo.ResultEntity;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * 用户控制器
 */
@RestController
@Slf4j
@RequestMapping("/api/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private IServerService serverService;
    @Resource
    private HttpSession httpSession;

    /**
     * 用户登录
     *
     * @param param 登录参数
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResultEntity<User> login(@RequestBody UserLoginParam param) {
        User user = userService.userLogin(param);
        user.setPassword(null);
        httpSession.setAttribute("loginUser", user);
        return ResultEntity.success("登录成功", user);
    }

    /**
     * 获取登录用户
     *
     * @return 登录的用户
     */
    @GetMapping("/getLoginUser")
    public ResultEntity<User> getLoginUser() {
        User loginUser = (User) httpSession.getAttribute("loginUser");
        loginUser.setPassword(null);
        return ResultEntity.success("获取登录用户成功", loginUser);
    }

    /**
     * 退出登录
     *
     * @return 退出登录结果
     */
    @PostMapping("/logout")
    public ResultEntity<Void> logout() {
        httpSession.invalidate();
        return ResultEntity.success("退出成功");
    }

    @GetMapping("/get/{userId}")
    public ResultEntity<User> getUser(@PathVariable String userId) {
        User loginUser = userService.getLoginUser();
        if (loginUser.getUserRole() == UserRole.ROLE_USER) {
            return ResultEntity.failed("无权限");
        }
        User user = userService.getById(userId);
        user.setPassword(null);
        return ResultEntity.success("获取用户成功", user);
    }

    @PostMapping("/reg")
    public ResultEntity<Void> reg(@RequestParam String token, @RequestBody User user, HttpServletRequest request) {
        if (!StringUtils.hasText(token)) {
            return ResultEntity.failed("请进行验证");
        }
        String captchaCode = (String) httpSession.getAttribute("captchaCode");
        if (captchaCode == null) {
            return ResultEntity.failed("请先请求验证码");
        }
        if (!token.equals(captchaCode)) {
            return ResultEntity.failed("验证码错误");
        }

        // 设置默认值
        user.setId(null);
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        user.setBalance(new BigDecimal("0"));
        user.setRegIp(request.getRemoteAddr());
        user.setRegTime(LocalDateTime.now());
        user.setUserRole(UserRole.ROLE_USER);

        // 去掉验证码
        httpSession.setAttribute("captchaCode", null);
        // 调用服务注册
        userService.userReg(user);
        return ResultEntity.success("注册成功,请登录");
    }

    @PostMapping("/list")
    public ResultEntity<IPage<User>> list(@RequestParam Integer current, @RequestBody User filterParam) {
        User loginUser = userService.getLoginUser();
        if (loginUser.getUserRole() != UserRole.ROLE_SUPER_ADMIN) {
            return ResultEntity.failed("无权限");
        }

        IPage<User> page = userService.pageUser(new Page<>(current, 20), filterParam);
        return ResultEntity.success("获取服务器列表成功", page);
    }

    @PostMapping("/updateInfo")
    public ResultEntity<User> updateInfo(UserUpdateInfoParam param) {
        return ResultEntity.success("test", null);
    }

    @PostMapping("/updatePass")
    public ResultEntity<Void> updatePass(@RequestBody UserUpdatePassParam param) {
        Integer userId = userService.getLoginUser().getId();
        // 更新密码
        userService.updatePass(userId, param);

        return ResultEntity.success("更新成功");
    }

    @PostMapping("/update")
    public ResultEntity<Void> update(@RequestBody UpdateUserParam param) {
        User loginUser = userService.getLoginUser();
        if (loginUser.getUserRole() != UserRole.ROLE_SUPER_ADMIN) {
            return ResultEntity.failed("无权限");
        }
        // 如果修改密码则转md5
        if (StringUtils.hasText(param.getPassword())) {
            param.setPassword(DigestUtils.md5DigestAsHex(param.getPassword().getBytes(StandardCharsets.UTF_8)));
        } else {
            param.setPassword(null);
        }

        // 构造属性
        User updateUser = new User();
        BeanUtils.copyProperties(param, updateUser);
        userService.updateById(updateUser);

        return ResultEntity.success("更新成功");
    }

    @PostMapping("/delete/{userId}")
    public ResultEntity<Void> delete(@PathVariable Integer userId) {
        User loginUser = userService.getLoginUser();
        if (loginUser.getUserRole() != UserRole.ROLE_SUPER_ADMIN) {
            return ResultEntity.failed("无权限");
        }

        userService.delete(userId);
        return ResultEntity.success("删除服务器成功");
    }
}
